package com.ynding.cloud.auth.authentication.service.api.impl;

import com.ynding.cloud.auth.api.authentication.api.IAuthApiService;
import com.ynding.cloud.auth.api.authentication.model.bo.AppInfo;
import com.ynding.cloud.auth.api.authentication.model.bo.UserInfo;
import com.ynding.cloud.auth.authentication.service.IAuthenticationService;
import com.ynding.cloud.auth.authentication.service.IRegLoginService;
import com.ynding.cloud.common.model.bo.ResponseBean;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

/**
 * <p> </p>
 *
 * @author ynding
 * @version 2021/8/17
 **/
@Slf4j
@DubboService(version = "1.0.0", timeout = 5000)
@RequiredArgsConstructor
public class AuthApiServiceImpl implements IAuthApiService {

    private final IAuthenticationService authenticationService;
    private final IRegLoginService regLoginService;

    @Override
    public ResponseBean register(UserInfo userInfo) {
        log.info("userInfo:{}", userInfo);
        String username = userInfo.getUsername();
        String password = userInfo.getPassword();
        return regLoginService.userReg(username, password);
    }

    @Override
    public ResponseBean<String> login(UserInfo userInfo) {
        log.info("userInfo:{}", userInfo);
        String username = userInfo.getUsername();
        String password = userInfo.getPassword();
        String token = authenticationService.getToken(username, password, AppInfo.APP_ID, AppInfo.APP_SECRET);
        return ResponseBean.ok(token);
    }

    @Override
    public ResponseBean refreshToken(String token) {
        log.info("token:{}", token);
        String newToken = authenticationService.refreshToken(token, AppInfo.APP_ID, AppInfo.APP_SECRET);
        return ResponseBean.ok(newToken);
    }

    @Override
    public ResponseBean<Boolean> auth(String authorization, String url, String method) {
        boolean permission = authenticationService.auth(authorization, url, method);
        return ResponseBean.ok(permission);
    }

    @Override
    public ResponseBean invalidJwtAccessToken(String access_token) {
        if (authenticationService.invalidJwtAccessToken(access_token)) {
            // 无效
            return ResponseBean.ok();
        }
        return ResponseBean.fail();
    }

    @Override
    public boolean hasPermission(String authentication, String url, String method) {
        //token是否有效
        if (this.invalidJwtAccessToken(authentication).getCode() == 200) {
            return Boolean.FALSE;
        }
        //从认证服务获取是否有权限
        ResponseBean responseBean = this.auth(authentication, url, method);
        return responseBean.getCode() == 200;
    }
}
